<template>
  <div class="flexColumn" style="overflow-y: scroll;margin-top: 60px">
    <el-card class="box-card card flexColumn" style="height: 150px;flex-shrink: 0;margin-top: -70px">
      <span class="mText">{{ careHomeName }}</span>
      <el-row style="margin-top: 20px">
        <el-col :span="8">
          <div class="flexColumn" style="align-items: center">
            <span class="lText" style="margin-bottom: 10px">{{ recordsData.todays ? '已生成' : '未生成' }} </span>
            <span class="sText">今日用药记录</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="flexColumn" style="align-items: center">
            <span class="lText" style="margin-bottom: 10px">{{ recordsData.notYet }}</span>
            <span class="sText">今日待执行用药记录数</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="flexColumn" style="align-items: center">
            <span class="lText" style="margin-bottom: 10px">{{ recordsData.count }}</span>
            <span class="sText">今日全部用药记录数</span>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <el-card class="box-card card flexColumn specialCard" style="margin-top: 20px;flex-shrink: 0">
      <div class="flexRow" style="margin-bottom: 20px;margin-top: 10px">
        <div style="margin-right: auto;margin-left: 20px">
          <el-input
              class="input"
              suffix-icon="el-icon-search"
              v-model="keyword"
              clearable
              @keydown.enter.native="search"
          />
          <el-dropdown @click="search()" size="large" split-button trigger="click" @command="handleClick">
            <span style="color: var(--btnText)">{{ btnWord }}</span>
            <el-dropdown-menu ref="dropdown" slot="dropdown" :append-to-body="false"
                              style="background-color: var(--lightBg)!important;border: none">
              <el-dropdown-item command="elder">根据老人姓名搜索</el-dropdown-item>
              <el-dropdown-item command="worker">根据护工姓名搜索</el-dropdown-item>
              <el-dropdown-item command="medication">根据药品名称搜索</el-dropdown-item>
              <el-dropdown-item command="create_time">根据生成日期搜索</el-dropdown-item>
              <el-dropdown-item command="status">根据服用状态搜索</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
        <div ref="here"></div>
        <div style="margin-left: auto;margin-right: 10px" class="flexRow">
          <el-button @click="openDialog">
            <i style="font-weight: bold;margin-right: 5px" class="el-icon-upload2"/>导出Excel
          </el-button>
          <el-button @click="generate" class="success">
            <i style="font-weight: bold;margin-right: 5px" class="el-icon-plus"/>
            生成今日用药记录
          </el-button>
        </div>
      </div>
      <el-table
          :data="records"
          :header-cell-style="{
                height: '70px'
              }"
          :row-style="{height: '62px'}">
        <el-table-column width="10px"/>
        <el-table-column
            label="记录生成日期">
          <template slot-scope="scope">
            {{ scope.row.createTime ? scope.row.createTime.slice(0, 10) : '未知日期' }}
          </template>
        </el-table-column>
        <el-table-column
            prop="elder.elderlyName"
            label="用药老人">
        </el-table-column>
        <el-table-column
            prop="medicationList.medication.name"
            label="服用药品">
          <template slot-scope="scope">
            {{ scope.row.medicationList ? scope.row.medicationList.medication.name : '未知药品' }}
          </template>
        </el-table-column>
        <el-table-column
            label="服用剂量">
          <template slot-scope="scope">
            <span>
              {{ scope.row.medicationList ? scope.row.medicationList.dosage : '未知剂量' }}
              {{ scope.row.medicationList ? scope.row.medicationList.unit : '' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
            prop="time"
            label="预定服用时间">
        </el-table-column>
        <el-table-column
            label="实际服用时间">
          <template slot-scope="scope">
            <span>{{ scope.row.updateTime ? scope.row.updateTime.slice(11, 19) : '--:--:--' }}</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="nurse.name"
            label="负责护工">
        </el-table-column>
        <el-table-column
            label="服用状态">
          <template slot-scope="scope">
            <span>{{ scope.row.status === 1 ? '已服用' : '未服用' }}</span>
          </template>
        </el-table-column>
        <el-table-column
            label="更新服用状态"
            class-name="cellClass"
            align="center">
          <template slot-scope="scope">
            <el-switch
                style="margin-top: 10px"
                @change="($event) => updateStatus($event, scope.row)"
                :value="scope.row.status === 1"
                active-color="var(--btn)"
                inactive-color="var(--th)">
            </el-switch>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          style="text-align: center;margin-top: 20px"
          background
          layout="prev, pager, next"
          :total="total"
          :pager-count="11"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="pageChange">
      </el-pagination>
    </el-card>
    <!--弹窗部分-->
    <el-dialog :visible.sync="dialog"
               :show-close="false"
               ref="dialog"
               class="dl"
               :limit="1"
               :modal-append-to-body='false'
               :append-to-body="false"
               @close="closeDialog">
      <h1 style="font-size: 24px;padding-top: 20px;color: var(--deepText)" align="center">选择导出内容</h1>
      <el-divider/>
      <div class="flexColumn" style="margin: 0 10% 0;padding: 3% 5% 1%;overflow-y: scroll;height: 340px">
        <div ref="choice0" @click="choose0" class="choice" style="margin-bottom: 40px">
          <span style="font-size: 18px">导出{{ careHomeName }}全部用药记录</span>
        </div>
        <div ref="choice1" @click="choose1" class="choice">
          <span style="font-size: 18px">选择导出某个老人的用药记录</span>
        </div>
        <div v-if="choice===1" class="flexRow" style="margin-top: 50px;">
          <span class="mText" style="font-size: 15px;line-height: 30px">选择要进行导出的老人： </span>
          <el-select
              style="width: 240px;margin-left: auto"
              v-model="chooseId"
              filterable
              remote
              reserve-keyword
              placeholder="请输入老人姓名进行搜索"
              :remote-method="getElders"
              :loading="loading">
            <el-option
                v-for="elder in elders"
                :key="elder.elderlyId"
                :label="elder.elderlyName"
                :value="elder.elderlyId">
              <el-row>
                <el-col :span="12">{{ elder.elderlyName }}</el-col>
                <el-col :span="4">{{ elder.sex }}</el-col>
                <el-col :span="8">{{ elder.bedNumber }}床</el-col>
              </el-row>
            </el-option>
          </el-select>
        </div>
      </div>
      <el-divider/>
      <div style="display: flex;flex-direction: row;margin-top: -20px">
        <el-button ref="btn" @click="exportRecords" class="formBtn" :disabled="choice===null">导出</el-button>
        <el-button @click="closeDialog" class="formBtn">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {serverIp} from "../../../../public/config";

export default {
  name: "MedicationRecords",
  data() {
    return {
      //养老院名称
      careHomeName: localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')).careHomeName : '',
      //药单记录
      records: [],
      recordsData: {},
      //分页相关
      currentPage: 1,
      pageSize: 7,
      total: 0,
      //搜索关键词
      keyword: '',
      searchMode: 'elder',
      //弹窗
      dialog: false,
      //ip
      serverIp: serverIp,
      //导出选中
      chooseId: '',
      elders: [],
      loading: false,
      //导出模式：1为导出某个老人，0为导出所有
      choice: null
    }
  },
  methods: {
    //换页
    pageChange(pageNum) {
      this.currentPage = pageNum
      this.search()
    },
    //获取数据
    load() {
      this.request.get('/medication-record/query-data?name=' + this.careHomeName).then(res => {
        if (res.code === '200') {
          this.recordsData = res.data
        } else {
          this.$notify({
            type: 'error',
            title: '获取用药记录信息失败',
            message: res.msg
          })
        }
      }).catch(err => {
        this.$notify({
          type: 'error',
          title: '获取用药记录信息失败',
          message: err
        })
      })
    },
    //搜索
    search() {
      //日志记录获取
      this.request.get('/medication-record/query', {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.keywordC,
          type: this.searchMode,
          name: this.careHomeName
        }
      }).then(res => {
        if (res.code === '200') {
          //成功
          this.records = res.data.records
          //将字符串属性转换为Long类型
          this.total = parseInt(res.data.total)
        } else {
          this.$notify({
            type: 'error',
            title: '获取用药记录失败',
            message: res.msg
          })
        }
      }).catch(err => {
        this.$notify({
          type: 'error',
          title: '获取用药记录失败',
          message: err
        })
      })
    },
    //修改搜索方式
    handleClick(command) {
      this.searchMode = command
    },
    //生成今日记录
    generate() {
      this.request.get('/medication-record/generate').then(res => {
        if (res.code === '200') {
          //成功
          if (this.recordsData.todays) {
            this.$notify({
              type: 'warning',
              title: '用药记录生成失败',
              message: '今日已生成过用药记录'
            })
          } else {
            this.$notify({
              type: 'success',
              title: '生成成功',
              message: '已生成今日记录'
            })
          }
          this.search()
          this.load()
        } else {
          this.$notify({
            type: 'error',
            title: '用药记录生成失败',
            message: res.msg
          })
        }
      }).catch(err => {
        this.$notify({
          type: 'error',
          title: '用药记录生成失败',
          message: err
        })
      })
    },
    //更新状态
    updateStatus(status, row) {
      const newStatus = row.status === 1 ? 0 : 1
      row.status = newStatus
      this.request.put('/medication-record/update-status?id=' + row.id + '&status=' + newStatus).then(res => {
        if (res.code === '200') {
          //成功
          this.$notify({
            type: 'success',
            title: '更新成功',
            message: '记录服用状态已更新'
          })
          this.load()
          this.search()
        } else {
          this.$notify({
            type: 'error',
            title: '记录服用状态更新失败',
            message: res.msg
          })
        }
      }).catch(err => {
        this.$notify({
          type: 'error',
          title: '记录服用状态更新失败',
          message: err
        })
      })
    },
    //弹窗
    openDialog() {
      this.dialog = true
    },
    closeDialog() {
      this.dialog = false
      this.chooseId = ''
      this.choice = null
      this.elders = []
      this.$refs.choice0.classList.remove('isChecked')
      this.$refs.choice1.classList.remove('isChecked')
    },
    //导出
    exportRecords() {
      window.location.href = 'https://' + serverIp + '/medication-record/export/' + this.careHomeName + '/' + this.chooseId;
    },
    //获取未分配药单的老人列表
    getElders(query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.request.get('/elderly-information/query-has-ml?careHomeName=' + this.careHomeName).then(res => {
            if (res.code === '200') {
              this.elders = res.data.filter(elder => {
                return elder.elderlyName.indexOf(query) > -1;
              })
            } else {
              this.$notify({
                type: 'error',
                title: '获取老人列表失败',
                message: res.msg
              })
            }
            this.loading = false
          }).catch(err => {
            this.$notify({
              type: 'error',
              title: '获取老人列表失败',
              message: err
            })
            this.loading = false
          })
        }, 200)
      } else {
        this.elders = []
      }
    },
    //选择全部导出
    choose0() {
      this.$refs.choice0.classList.add('isChecked')
      this.$refs.choice1.classList.remove('isChecked')
      this.choice = 0
      this.chooseId = 0
      this.elders = []
    },
    choose1() {
      this.$refs.choice1.classList.add('isChecked')
      this.$refs.choice0.classList.remove('isChecked')
      this.choice = 1
      this.chooseId = ''
    }

  },
  mounted() {
    this.search()
    this.load()
    //修改popper的所在位置
    this.$refs.here.appendChild(
        this.$refs.dropdown.popperElm
    )
  },
  computed: {
    //根据关键词类型显示按钮提示文字和图标
    btnWord() {
      switch (this.searchMode) {
        case 'elder':
          return '根据老人姓名搜索'
        case 'worker':
          return '根据护工姓名搜索'
        case 'medication':
          return '根据药品名称搜索'
        case 'create_time':
          return '根据生成日期搜索'
        case 'status':
          return '根据服用状态搜索'
        default:
          return '搜索'
      }
    },
    //如果根据服用状态来搜索，将关键词更换为integer型
    keywordC() {
      if (this.searchMode === 'status') {
        if (this.keyword === '已服用' || this.keyword === '已' || this.keyword === '1') {
          return 1
        } else if (this.keyword === '未服用' || this.keyword === '未' || this.keyword === '0') {
          return 0
        } else if (this.keyword === '服用' || this.keyword === '服' || this.keyword === '用') {
          return ''
        } else {
          return this.keyword
        }
      } else {
        return this.keyword
      }
    }
  },
}
</script>

<style scoped>
/*card*/
>>> .el-card__header {
  border-color: var(--deepText);
}

.box-card:hover {
  background-color: var(--hover);
}

.card {
  background-color: var(--lightBg);
  border: 1px solid var(--inputBorder);
  color: var(--deepText);
}

/*文字*/
.sText {
  font-size: 13px;
  color: var(--lightText);
}

.lText {
  font-size: 24px;
  color: var(--deepText);
}

.mText {
  font-size: 18px;
  color: var(--deepText);
}

/*滚动条*/
::-webkit-scrollbar {
  overflow: auto;
  width: 10px;
}

::-webkit-scrollbar-thumb {
  background-color: var(--th);
  border-radius: 5px;
}

::-webkit-scrollbar-thumb:hover {
  background-color: var(--lightText);
}

/*表格样式*/
/*表头背景*/
>>> .el-table .cell {
  height: 20px;
}

>>> .el-table th {
  background-color: var(--lightBg) !important;
}

/*表头文字*/
>>> .el-table thead {
  color: var(--th)
}

/*背景*/
>>> .el-table tr {
  background-color: var(--lightBg);
  color: var(--deepText);
  font-weight: normal;
}

/*行间线*/
>>> .el-table td, .building-top .el-table th.is-leaf {
  border-bottom: 0 !important;
}

/*表格末尾*/
>>> .el-table::before {
  border-bottom: 0;
  height: 0;
}

>>> .el-table, .el-table__expanded-cell {
  background-color: var(--lightBg) !important;
}

/*鼠标悬浮*/
>>> .el-table tbody tr:hover > td {
  background-color: var(--hover) !important;
}

/*操作列样式*/
>>> td.cellClass .cell {
  height: 34px !important;
}

.specialCard:hover {
  background-color: var(--lightBg);
}

/*分页管理器样式*/
>>> .btn-quicknext, >>> .btn-quickprev, >>> .btn-next, >>> .btn-prev, >>> .number {
  color: var(--deepText) !important;
  background-color: var(--deepBg) !important;
}

>>> .btn-quicknext:hover, >>> .btn-quickprev:hover, >>> .btn-next:hover, >>> .btn-prev:hover, >>> .number:hover {
  background-color: var(--hover) !important;
}

>>> .active {
  background-color: var(--btn) !important;
  color: var(--btnText) !important;
}

>>> .active:hover {
  background-color: var(--btnActive) !important;
}

/*搜索按钮*/
>>> .el-button--default {
  font-size: 13px;
  font-weight: bold;
  background-color: var(--btn);
  color: var(--btnText);
  border: none;
  transition: 0.2s;
}

>>> .el-button--default:hover {
  background-color: var(--btnActive);
}

>>> .el-button--default::before {
  display: none;
}

/*下拉框样式*/
>>> .el-dropdown__caret-button {
  font-size: 13px;
  font-weight: bold;
  margin-left: 2px !important;
  color: var(--btnText);
}

>>> .el-dropdown-menu {
  background-color: var(--inputBg) !important;
  padding: 0;
}

>>> .popper__arrow, >>> .popper__arrow::after {
  border-bottom-color: var(--inputBg) !important;
  border-top-color: var(--inputBg) !important;
}

>>> .el-dropdown-menu__item {
  color: var(--deepText);
  font-weight: bold;
  padding: 10px 30px;
  background-color: var(--inputBg);
}

>>> .el-dropdown-menu__item:hover {
  background-color: var(--hover);
  color: var(--deepText);
}

>>> .el-dropdown > .el-button-group > .el-button:not(:last-child) {
  width: 148px;
}

/*输入框样式*/
.input {
  margin-right: 20px;
  width: 300px;
  justify-content: center;
  align-items: center;
  border-radius: 5px;
}

>>> .el-input__inner {
  color: var(--deepText);
  background-color: var(--inputBg);
  border: solid 1px var(--inputBorder);
  border-radius: 5px;
}

>>> .el-date-editor .el-input__inner::placeholder {
  color: var(--lightText);
  padding-left: 10px;
}

>>> .el-input__icon {
  color: var(--deepText);
}


.primary {
  background-color: var(--btn);
}

.primary:hover {
  background-color: var(--btnActive);
}

.danger {
  background-color: var(--dangerHover);
}

.danger:hover {
  background-color: var(--danger);
}

.success {
  background-color: var(--success);
}

.success:hover {
  background-color: var(--successHover);
}

.resource {
  background-color: var(--resource);
}

.resource:hover {
  background-color: var(--resourceHover);
}

/*弹窗样式*/
>>> .el-dialog {
  background-color: var(--lightBg);
  border-radius: 10px;
  height: 560px;
  width: 650px;
  margin-top: calc(20% - 200px) !important;
}

>>> .el-dialog__body {
  height: 100%;
  padding: 0;
}

>>> .el-dialog__header {
  height: 0;
  padding: 0;
}

>>> .el-dialog__wrapper {
  transition-duration: 0.3s;
}

>>> .dialog-fade-enter-active {
  animation: none !important;
}

>>> .dialog-fade-leave-active {
  transition-duration: 0.15s !important;
  animation: none !important;
}

>>> .dialog-fade-enter-active .el-dialog,
.dialog-fade-leave-active .el-dialog {
  animation-fill-mode: forwards;
}

>>> .dialog-fade-enter-active .el-dialog {
  animation-duration: 0.3s;
  animation-name: anim-open;
  animation-timing-function: cubic-bezier(0.6, 0, 0.4, 1);
}

>>> .dialog-fade-leave-active .el-dialog {
  animation-duration: 0.3s;
  animation-name: anim-close;
}

@keyframes anim-open {
  0% {
    opacity: 0;
    transform: scale3d(0, 0, 1);
  }
  100% {
    opacity: 1;
    transform: scale3d(1, 1, 1);
  }
}

@keyframes anim-close {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
    transform: scale3d(0.5, 0.5, 1);
  }
}

/*表单按钮样式*/
.formBtn {
  color: var(--btnText);
  margin: 20px auto;
  width: 140px;
  height: 40px;
  background-color: var(--btn);
  transition: 0.2s;
  font-size: 13px;
  font-weight: bold;
  border: none;
}

.formBtn:hover {
  background-color: var(--btnActive);
}

>>> .el-form-item__label {
  color: var(--deepText);
}

.choice {
  background-color: var(--deepBg);
  padding: 20px 0;
  border: solid 2px var(--btn);
  border-radius: 10px;
  text-align: center;
  cursor: pointer;
  transition: 0.2s;
}

.choice:hover {
  background-color: var(--hover);
}

.isChecked {
  background-color: var(--btn);
  color: var(--btnText);
}

.isChecked:hover {
  background-color: var(--btnActive);
}

>>> .el-input__inner::placeholder {
  color: var(--lightText);
}

>>> .is-disabled {
  opacity: 0.5;

}
</style>